package com.guang.lock.await;

import com.guang.lock.ReentrantLockDemo2;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author lg
 * @Description
 * @date 2022/10/31 15:38
 */
public class LockWaitATestOne {

    private static Logger logger = LoggerFactory.getLogger(LockWaitATestOne.class);

    static volatile boolean flag = false;

    private static ReentrantLock lock = new ReentrantLock();

    static Condition condition = lock.newCondition();

    public static void main(String[] args) throws InterruptedException {
        logger.info("当前在主线程中");

        Thread t1 = new Thread(() -> {
            lock.lock();
            logger.info("t1线程拿到了锁");
            try {
                while (!flag){
                    logger.info("当前标记不满足条件");
                    try {
                        // 释放了锁！会释放锁，然后时间过后会再次获取得到锁
                        condition.await(500, TimeUnit.SECONDS);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }finally {
                lock.unlock();
            }
        }, "t1");

        t1.start();
        // TimeUnit.SECONDS.sleep(5);
        TimeUnit.MILLISECONDS.sleep(1000);
        Thread t2 = new Thread(() -> {
            lock.lock();
            logger.info("t2线程拿到了锁");
            try {
                while (!flag){
                    logger.info("修改当前条件");
                    flag = true;
                    condition.signal();
                }
            }finally {
                lock.unlock();
            }
        }, "t2");
        t2.start();

    }
}
